﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using PS.WssSync.Utils;

namespace PS.WssSync
{
    public class WssSyncConfig
    {
        private const string configFileName = "WssSync.options";
        private readonly List<Filter> allowFilters = new List<Filter>();
        private readonly List<Filter> ignoreFilters = new List<Filter>();
               
        public string SiteLocation { get; set; }

        [
            XmlArrayItem(typeof(Extension)),
            XmlArrayItem(typeof(Regexp)),
            XmlArrayItem(typeof(Folder))
        ]
        public List<Filter> AllowFilters
        {
            get { return allowFilters; }
        }

        [
            XmlArrayItem(typeof(Extension)),
            XmlArrayItem(typeof(Regexp)),
            XmlArrayItem(typeof(Folder))
        ]
        public List<Filter> IgnoreFilters
        {
            get { return ignoreFilters; }
        }

        internal static WssSyncConfig GetConfig(AppProperties properties, bool createNewConfig)
        {
            string configFilePath = string.Join("\\", new[] { properties.DirPath.TrimEnd(new[] { '\\' }), configFileName });
            var helper = new XmlSerializationHelper<WssSyncConfig>();
            WssSyncConfig syncConfig = null;            

            if(File.Exists(configFilePath))
            {
                syncConfig = helper.DeserializeFromFile(configFilePath);
            }
            else if(createNewConfig)
            {
                syncConfig = new WssSyncConfig();
                syncConfig.SiteLocation = properties.DirUrl;

                string directory = Path.GetDirectoryName(configFilePath);
                if(!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                const string pattern = "xmlns:.*\\\".*\\\"";
                StringBuilder configContent = new StringBuilder();
                configContent.Append (Regex.Replace(helper.Serialize(syncConfig), pattern, string.Empty, RegexOptions.Singleline));
                configContent.Append(ConfigHelp);
                File.WriteAllText(configFilePath, configContent.ToString());                
            }

            return syncConfig;
        }
       
        private static string ConfigHelp
        {
            get
            {
                return @"
<!--

Example of usage:

<SiteLocation>http://localhost</SiteLocation>
<AllowFilters>
    <Extension>.aspx</Extension>
    <Folder>.</Folder>
    <Regexp>.+\.aspx</Regexp>
  </AllowFilters>
  <IgnoreFilters>
    <Extension>.xml</Extension>
    <Folder>Pages</Folder>
    <Regexp>.+\.xml</Regexp>
  </IgnoreFilters>

-->";
            }
            
        }
    }
}
